# -*- coding: utf-8 -*-

#################
#    Imports    #
#################
from PyQt4 import QtCore, QtGui
from appui import Ui_MainWindow
from DatabaseMngr import *
from DataMngr import *

import webbrowser

start_time = time.time()
end_time = None

# Code URL
REPOSITORIO = 'https://code.google.com/p/lp1314-11903-11906/'
datamngr = None
databasemngr = None


def init_data():
    """
    Main data classes
    """
    global datamngr
    datamngr = DataMngr()

    # Load data from xls and dump to console and files
    datamngr.load_from_xls('data/cna131fresultados.xls')
    datamngr.dump('data/data_dump.txt')
    datamngr.dump_csv('data/estatistica')


def init_database():
    """
    Initalizes the sqlite database and insert all avaliable data
    """
    global databasemngr
    databasemngr = DatabaseMngr()
    for data in datamngr.data:
        databasemngr.insert_escola(data)

    # Commit changes to db
    databasemngr.commit()

# Profile and calls a function
cProfile.run("init_data()", 'data/init_data.profile')
# Profile and calls a function
cProfile.run("init_database()", 'data/init_database.profile')


class App(QtGui.QMainWindow):
    """
    Applicatiom main window
    """
    def __init__(self, parent=None):
        """
        Constructor
        """

        # Initializes APP GUI
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Connect buttons with click event and trigger a function
        QtCore.QObject.connect(self.ui.actionRepositorio_aplicacao,
                               QtCore.SIGNAL('triggered()'), self.open_app_website)

        QtCore.QObject.connect(self.ui.actionExportar_para_CSV,
                               QtCore.SIGNAL('triggered()'), self.export_data_csv)

        QtCore.QObject.connect(self.ui.actionExportar_para_TXT,
                               QtCore.SIGNAL('triggered()'), self.export_data_txt)

        QtCore.QObject.connect(self.ui.actionNumero_alunos_colocados_por_instituicao,
                               QtCore.SIGNAL('triggered()'), datamngr.plot_colocados_por_instituicao)

        QtCore.QObject.connect(self.ui.actionPercentagem_alunos_colocados_por_instituicao_em_relacao_a_todos_os_alunos_colocados,
                               QtCore.SIGNAL('triggered()'), datamngr.plot_percentagem_colocados_por_instiuicao)

        QtCore.QObject.connect(self.ui.actionNumero_vagas_por_colocar_por_instituicao,
                               QtCore.SIGNAL('triggered()'), datamngr.plot_vagas_por_colocar_por_instiuicao)

        QtCore.QObject.connect(self.ui.actionNumero_alunos_colocados_por_distrito,
                               QtCore.SIGNAL('triggered()'), datamngr.plot_alunos_colocados_por_distrito)

        QtCore.QObject.connect(self.ui.actionPermilagem_de_alunos_colocados_por_distrito,
                               QtCore.SIGNAL('triggered()'), datamngr.plot_permilagem_de_alunos_colocados_por_distrito)

        QtCore.QObject.connect(self.ui.actionNumero_vagas_por_colocar_por_distrito,
                               QtCore.SIGNAL('triggered()'), datamngr.plot_vagas_por_colocar_por_distrito)

        # Populate tree list view on app gui with data
        for key, value in datamngr.dataparsed.iteritems():
            # Instituto
            item = QtGui.QTreeWidgetItem(self.ui.trv_data)
            fontbold = QtGui.QFont()
            fontbold.setBold(True)
            item.setFont(0, fontbold)
            item.setFont(1, fontbold)
            item.setFont(2, fontbold)
            item.setFont(3, fontbold)
            item.setText(0, key)
            item.setText(1, str(value['totalcolocados']))
            item.setText(2, str(value['totalvagasiniciais']))
            item.setText(3, str(value['totalvagasrestantes']))

            for keycurso, valuecurso in value['cursos'].iteritems():
                # Cursos
                item_curso = QtGui.QTreeWidgetItem(item)
                item_curso.setText(0, u"{0} - {1}".format(keycurso, valuecurso['nome']))
                item_curso.setText(1, str(valuecurso['colocados']))
                item_curso.setText(2, str(valuecurso['vagasiniciais']))
                item_curso.setText(3, str(valuecurso['vagasrestantes']))
                #item_1 = QtGui.QTreeWidgetItem(item_0)

        # Populate tree list view on app gui with districts data
        for key, value in datamngr.stats['districts'].iteritems():
            item = QtGui.QTreeWidgetItem(self.ui.trv_districts)
            item.setText(0, key)
            item.setText(1, str(value['cursos']))
            item.setText(2, str(value['totalcolocados']))
            item.setText(3, str(value['totalvagasiniciais']))
            item.setText(4, str(value['totalvagasrestantes']))

        global end_time
        end_time = time.time()-start_time

        self.ui.statusbar.addWidget(QtGui.QLabel(u' Instituições: {0} '.format(len(datamngr.dataparsed))))
        self.ui.statusbar.addWidget(QtGui.QLabel(u' Distritos: {0} '.format(len(datamngr.districts))))
        self.ui.statusbar.addWidget(QtGui.QLabel(u' Aplicação carregada em: {0:.4f}ms '.format(end_time)))

    def export_data_csv(self):
        """
        Export data to csv files
        """

        # Save file dialog
        filename = QtGui.QFileDialog.getSaveFileName(QtGui.QFileDialog(), "Save data as csv files", "", "")
        # Check if file is valid
        if filename is None:
            return False
        if filename == '':
            return False

        # Save to file
        datamngr.dump_csv(str(filename.toUtf8()))
        return True

    def export_data_txt(self):
        """
        Export data to a txt file
        """

        # Save file dialog
        filename = QtGui.QFileDialog.getSaveFileName(QtGui.QFileDialog(), "Save data as txt file", "", ".txt")
        # Check if file is valid
        if filename is None:
            return False
        if filename == '':
            return False

        # Save to file
        datamngr.dump(str(filename.toUtf8()))
        return True

    def open_app_website(self):
        """
        Open application website in a new page
        """

        webbrowser.open_new(REPOSITORIO)

# Main application call
if __name__ == "__main__":
    # Initializes application gui
    app = None
    myapp = None

    # profile application gui creation
    cProfile.run('app = QtGui.QApplication(sys.argv); myapp = App()', 'data/ini_app_gui.profile')

    # Try to parse .profile files and write it in a human readable file
    try:
        with open('data/init_data.txt', 'w') as f:
            f.write('# Profiler for data initialization, parse and dump to console and a file\n\n')
            stats = pstats.Stats('data/init_data.profile', stream=f)
            stats.strip_dirs()
            stats.sort_stats('cumulative')
            stats.print_stats()

        with open('data/init_database.txt', 'w') as f:
            f.write('# Profiler for database initialization and insert results\n\n')
            stats = pstats.Stats('data/init_database.profile', stream=f)
            stats.strip_dirs()
            stats.sort_stats('cumulative')
            stats.print_stats()

        with open('data/ini_app_gui.txt', 'w') as f:
            f.write('# Profiler for app gui initialization\n\n')
            stats = pstats.Stats('data/ini_app_gui.profile', stream=f)
            stats.strip_dirs()
            stats.sort_stats('cumulative')
            stats.print_stats()
    except:
        print "Error trying profile applcation calls"

    # Show application GUI
    myapp.show()

    # Exit
    sys.exit(app.exec_())
